package servlet;

import bean.Student;
import service.StudentService;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(name = "StudentQueryServlet",urlPatterns = "/StudentQueryServlet")
public class StudentQueryServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.获取请求中的学生并打印出来
        String id = request.getParameter("id");
        System.out.println("获取到的学号是：" + id);
        String name = request.getParameter("name");
        System.out.println("获取到的姓名是：" + name);
        String sex = request.getParameter("sex");
        System.out.println("获取到的性别是：" + sex);
        String date = request.getParameter("date");
        System.out.println("获取到的出生日期是：" + date);
        String email = request.getParameter("email");
        System.out.println("获取到的邮箱是：" + email);
        String remarks = request.getParameter("remarks");
        System.out.println("获取到的备注是：" + remarks);
        //2.创建StudentService类型的对象去实现数据的校验功能
        StudentService studentService = new StudentService();
        Student student = studentService.studentAddService(new Student(name, sex, date, email, remarks));
        if (null == student){
            System.out.println("学生信息查询失败！");
            request.setAttribute("error","学生信息查询失败！");
            //实现服务器跳转 共享request和response对象
            RequestDispatcher requestDispatcher = request.getRequestDispatcher("manageStudent.jsp");
            requestDispatcher.forward(request,response);
        }else{
            System.out.println("学生信息查询成功！");
            //将查询成功的学生信息放入session对象中实现多个请求的共享
            request.getSession().setAttribute("student",student);
            //实现客户端跳转
            response.sendRedirect("manageStudent.jsp");
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
